package com.sinnatec.redis.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

/**
 * @ClassName SpelUtil
 * @Description SPEL表达式解析
 * @Author fangsong
 * @Date 2021/12/8 11:35
 * @Version 1.0
 */
public class SpelUtil {

    private static final String SPEL_CHARACTER = "#";

    private static final SpelExpressionParser parser = new SpelExpressionParser();
    private static final DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();

    private SpelUtil(){
    }

    public static String evaluate(String spelKey, String [] paramNames, Object [] args){
        if (paramNames != null && paramNames.length > 0) {
            // spring的表达式上下文对象
            EvaluationContext context = new StandardEvaluationContext();
            // 通过joinPoint获取被注解方法的形参
            // 给上下文赋值
            for (int i = 0; i < args.length; i++) {
                context.setVariable(paramNames[i], args[i]);
            }
            // 解析过后的Spring表达式对象
            Expression expression = parser.parseExpression(spelKey);
            Object expressionValue = expression.getValue(context);
            if (expressionValue == null) {
                return null;
            }
            return String.valueOf(expressionValue);
        }
        return null;
    }

    public static String evaluate(String spelKey, Method method, Object [] args){
        if(StringUtils.indexOf(spelKey,SPEL_CHARACTER)>-1){
            return evaluate(spelKey,discoverer.getParameterNames(method),args);
        }
        else{
            return spelKey;
        }
    }


}
